package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.ClassApplication;
import com.example.temp.entity.ClassEntity;
import com.example.temp.mapper.ClassApplicationMapper;
import com.example.temp.mapper.ClassMapper;
import com.example.temp.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/class/application")
public class ClassApplicationController {

    @Autowired
    private ClassApplicationMapper classApplicationMapper;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private ClassMapper classMapper;

    // 学生申请加入班级
    @PostMapping("/apply")
    public Result applyClass(@RequestBody ClassApplication application) {
        try {
            // 检查是否已经存在待处理的申请
            int pendingCount = classApplicationMapper.countPendingApplication(
                    application.getClassId(), application.getStudentId());
            if (pendingCount > 0) {
                return Result.fail("您已经提交过申请，请等待教师审核");
            }
            
            // 检查学生是否已经在班级中
            int inClassCount = classApplicationMapper.checkStudentInClass(
                    application.getClassId(), application.getStudentId());
            if (inClassCount > 0) {
                return Result.fail("您已经在该班级中，无需再次申请");
            }
            
            // 设置初始状态为待处理
            application.setStatus("pending");
            application.setApplyTime(new Date());
            
            int result = classApplicationMapper.insert(application);
            if (result > 0) {
                return Result.success("申请提交成功，请等待教师审核");
            } else {
                return Result.fail("申请提交失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("申请提交出错：" + e.getMessage());
        }
    }
    
    // 教师处理班级申请
    @PutMapping("/handle/{applicationId}")
    public Result handleApplication(
            @PathVariable Integer applicationId,
            @RequestBody Map<String, Object> params) {
        try {
            String status = (String) params.get("status");
            String remark = (String) params.get("remark");
            String teacherId = (String) params.get("teacherId");
            
            if (status == null || !status.matches("approved|rejected")) {
                return Result.fail("状态参数错误");
            }
            
            // 获取申请详情
            ClassApplication application = classApplicationMapper.findById(applicationId);
            if (application == null) {
                return Result.fail("申请不存在");
            }
            
            if (!"pending".equals(application.getStatus())) {
                return Result.fail("该申请已处理，不能重复处理");
            }
            
            // 更新申请状态
            application.setStatus(status);
            application.setHandleTime(new Date());
            application.setHandleTeacherId(teacherId);
            application.setRemark(remark);
            
            int result = classApplicationMapper.updateStatus(application);
            
            // 如果是批准申请，将学生添加到班级
            if ("approved".equals(status) && result > 0) {
                try {
                    // 首先获取班级信息以获取班级名称
                    ClassEntity classEntity = classMapper.findById(application.getClassId());
                    if (classEntity != null) {
                        // 使用完整的班级信息更新学生记录
                        int updateResult = studentMapper.updateClassInfo(
                            application.getStudentId(),
                            classEntity.getClassName(), // 使用正确的班级名称
                            application.getClassId()
                        );
                        
                        if (updateResult <= 0) {
                            // 记录错误但不阻止流程
                            System.err.println("无法更新学生班级信息: " + application.getStudentId());
                        }
                    } else {
                        System.err.println("找不到班级信息: " + application.getClassId());
                    }
                } catch (Exception ex) {
                    // 记录错误但不阻止流程
                    System.err.println("更新学生班级信息时出错: " + ex.getMessage());
                    ex.printStackTrace();
                }
            }
            
            if (result > 0) {
                return Result.success("申请处理成功");
            } else {
                return Result.fail("申请处理失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("申请处理出错：" + e.getMessage());
        }
    }
    
    // 查询班级的申请列表
    @GetMapping("/class/{classId}")
    public Result getClassApplications(
            @PathVariable Integer classId,
            @RequestParam(required = false) String status) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("classId", classId);
            params.put("status", status);
            
            List<ClassApplication> applications = classApplicationMapper.findByClassId(params);
            return Result.success(applications);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询班级申请列表出错：" + e.getMessage());
        }
    }
    
    // 查询学生的申请列表
    @GetMapping("/student/{studentId}")
    public Result getStudentApplications(
            @PathVariable String studentId,
            @RequestParam(required = false) String status) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            params.put("status", status);
            
            List<ClassApplication> applications = classApplicationMapper.findByStudentId(params);
            return Result.success(applications);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询学生申请列表出错：" + e.getMessage());
        }
    }
}
